import {Server, Socket} from 'socket.io'

/**
 * @type {Map<string, Set<string>>}
 */
const roomMap = new Map()

/**
 * 初始化 SDP 服务器
 * @param {Server} io
 */
export const initSDPServer = io => {
    // 当用户连接到客户端时触发该事件
    io.on('connection', socket => {
        console.log('New client connected')
        onEvent(socket)
    })
}

/**
 * 初始化事件监听
 * @param {Socket} socket
 */
const onEvent = socket => {
    const {roomId, userId} = socket.request._query
    console.log(' socket.request._query;', socket.request._query)
    // 处理接收到的 SDP offer
    socket.on('offer-sdp-msg', data => {
        console.log('Received offer from', userId)
        socket.to(roomId).emit('offer-sdp-msg', data)
    })

    // 处理接收到的 SDP answer
    socket.on('answer-sdp-msg', data => {
        console.log('Received answer from', userId)
        socket.to(roomId).emit('answer-sdp-msg', data)
    })

    // 处理 ICE candidate 消息
    socket.on('candidate-msg', data => {
        console.log('Received ICE candidate from', userId)
        socket.to(roomId).emit('candidate-msg', data)
    })

    // 处理用户断开连接
    socket.on('disconnect', () => {
        console.log('Client disconnected', userId)
        socket.to(roomId).emit('client-leave', `${userId}: leave`)
        roomMap.get(roomId).delete(userId)
        console.log('房间总人数', roomMap, roomMap.get(roomId).size)
    })

    // 加入房间并维护用户集合
    const userSet = roomMap.get(roomId)
    if (!userSet) {
        const newUserSet = new Set()
        newUserSet.add(userId)
        roomMap.set(roomId, newUserSet)
    } else {
        userSet.add(userId)
    }

    socket.join(roomId)
    console.log([...roomMap.get(roomId)], roomMap, roomMap.get(roomId))
    socket.emit('user-id-list-msg', Array.from(roomMap.get(roomId)))
    socket.to(roomId).emit('user-id-list-msg', [...roomMap.get(roomId)])
    socket.to(roomId).emit('room-msg', `我来了 ${userId}`)
    console.log('房间总人数', roomMap.get(roomId).size)
}
